/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.scriptmark.core.dispose;

import com.jspx.scriptmark.Phrase;
import com.jspx.scriptmark.ScriptRunner;
import com.jspx.scriptmark.core.TagNode;
import com.jspx.scriptmark.core.EnvRunner;
import com.jspx.scriptmark.core.block.SwitchBlock;
import com.jspx.scriptmark.core.block.DefaultBlock;
import com.jspx.scriptmark.core.block.CaseBlock;
import com.jspx.scriptmark.exception.ScriptRunException;
import com.jspx.utils.ObjectUtil;
import java.io.Writer;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: chenYuan
 * Date: 2009-1-2
 * Time: 16:23:52
 */
public class SwitchPhrase implements Phrase {


    public SwitchPhrase() {

    }

    public int getRun(EnvRunner env, TagNode tagNode, Writer out) throws Exception
    {
        ScriptRunner scriptEngine = env.getScriptRunner();
        boolean isRun = false;
        SwitchBlock switchBlock = (SwitchBlock) tagNode;
        DefaultBlock defaultBlock = null;
        String check = switchBlock.getVarName();
        List<TagNode> caseList = switchBlock.getCaseAndDefaultBlock();

        for (TagNode cNode : caseList) {
            if (cNode instanceof CaseBlock) {
                CaseBlock caseblock = (CaseBlock) cNode;
                if (ObjectUtil.toBoolean(scriptEngine.eval(check + "==" + caseblock.getWhere(),switchBlock.getLineNumber()))) {
                    isRun = true;
                    for (TagNode node : caseblock.getChildList()) {
                        try{
                            env.runBlock(node, out);
                        }catch (Exception e) {
                            throw new ScriptRunException(node,tagNode.getTagName());
                        }
                    }
                    break;
                }
            } else if (cNode instanceof DefaultBlock) {
                defaultBlock = (DefaultBlock) cNode;
            }
        }
        if (!isRun && defaultBlock != null) {
            for (TagNode dNode : defaultBlock.getChildList()) {
                try{
                    env.runBlock(dNode, out);
                } catch (Exception e) {
                    throw new ScriptRunException(dNode,tagNode.getTagName());
                }
            }
        }
        caseList.clear();
        return 0;
    }
}